#include "Manager.h"

unsigned int Manager::getResourceIndex(Resource* id)
{
	unsigned int i = 0;
	for(i = 0; i < resources.size(); i++)
		if(id->getID()==resources[i].getID())
			return i;
	return -1;
}

unsigned int Manager::getResourceIndex(unsigned int id, bool idOrCode)
{
	if(idOrCode == true) //use the id
	{
		unsigned int i = 0;
		for(i = 0; i < resources.size(); i++)
			if(id==resources[i].getID())
				return i;
		return -1;
	}
	else
	{
		unsigned int i = 0;
		for(i = 0; i < resources.size(); i++)
			if(id==resources[i].getCode())
				return i;
		return -1;
	}
}

Resource* Manager::registerResource(Resource* id)
{
	unsigned int i = getResourceIndex(id);
	if(i==((unsigned int) -1))
	{
		resources.push_back(id);
		owners.push_back(NULL);
		requestors.push_back(Vector<Identifier*>());
		requestorStates.push_back(Vector<unsigned char>());
		return &(resources[resources.size()-1]);
	}
	else
		return &(resources[i]);
	
}


Resource* Manager::getResourceById(unsigned int id)
{
	unsigned int i = getResourceIndex(id, true);
	unsigned int j = -1;
	if(i==j)
		return NULL;
	else
		return &(resources[i]);
}

Resource* Manager::getResourceByCode(unsigned int code)
{
	unsigned int i = getResourceIndex(id, false);
	unsigned int j = -1;
	if(i==j)
		return NULL;
	else
		return &(resources[i]);
}

Vector<Owner*>* getRequestorsById(unsigned int id)
{
	unsigned int i = getResourceIndex(id, true);
	unsigned int j = -1;
	if(i==j)
		return NULL;
	else
		return &(requestors[i]);
}

Vector<Owner*>* getRequestorsByCode(unsigned int id)
{
	unsigned int i = getResourceIndex(id, false);
	unsigned int j = -1;
	if(i==j)
		return NULL;
	else
		return &(requestors[i]);
}


Vector<unsigned char>* getStatesById(unsigned int id)
{
	unsigned int i = getResourceIndex(id, true);
	unsigned int j = -1;
	if(i==j)
		return NULL;
	else
		return &(requestorStates[i]);
}

Vector<unsigned char>* getStatesByCode(unsigned int id)
{
	unsigned int i = getResourceIndex(id, false);
	unsigned int j = -1;
	if(i==j)
		return NULL;
	else
		return &(requestorStates[i]);
}

Vector<Owner*>* registerRequestor(Resource* resource,
					Owner* requestor)
{
	unsigned int i = getResourceIndex(resource);
	unsigned int j = -1;
	if(i == j )
		return NULL;
	else
	{
		//check if the requestor already exists
		unsigned int k = 0;
		for(k = 0; k < requestors[i].size(); k++)
			if(requestors[i][k].getID() == requestor.getID())
				return &(requestors[i]);
		//add the requestor now
		requestors[i].push_back(requestor);
		return &(requestors[i]);
	}
}


